import os
import ddddocr
import base64
import jsonpath
import requests
from PIL import Image
import sys

def get_auth_captcha():
    # 重新获取验证码的接口
    payload = {
        "method": "get",
        "url": os.environ["URL"] + "/auth/captcha",
    }
    response = requests.request(**payload).json()
    sn = jsonpath.jsonpath(response, "$..sn")[0]
    image = jsonpath.jsonpath(response, "$..image")[0]
    return sn, image



def dddd_ocr_text(image):
    try:
        # 步骤1. 需要对 image 进行分割，得到头部和 Base64 编码的部分
        encode_data = image.split(",")[1]

        # 步骤2：解码 Base64 元数据
        decode_data = base64.b64decode(encode_data)

        # 步骤3：通过 ddddocr 来识别图片元数据
        ocr = ddddocr.DdddOcr()
        text = ocr.classification(decode_data)
        return text
    except Exception as e:
        print(f"OCR识别失败: {e}")
        return None

# 存放全局的验证码文本和sn文本
sn_captcha_text = {}

# 执行次数
run_nums = 0

# 获取验证码和 sn 的最终方法
def get_res_sn_captcha():
    if os.environ["ENV"] == "prod":
        global run_nums
        # 判断第一次执行的时候和失败重试的时候才会执行下面的获取验证码和 sn 的逻辑
        if not sn_captcha_text or run_nums % 2 == 0:
            sn, image = get_auth_captcha()
            captcha = dddd_ocr_text(image)
            sn_captcha_text["sn"] = sn
            sn_captcha_text["captcha"] = captcha

        run_nums += 1

        return sn_captcha_text
    elif os.environ["ENV"] == "test":
        sn = get_auth_captcha()[0]
        sn_captcha_text["sn"] = sn
        sn_captcha_text["captcha"] = "aaaa"
        return sn_captcha_text


if __name__ == '__main__':
    image = ""
    # text = dddd_ocr_text(image)
    # print(f"识别结果: {text}")
    str1 = "dddd_ocr_text(image)"
    print(str1)
    print(eval(str1))